import { createRouter, createWebHistory } from 'vue-router'
import { useStore } from 'vuex';
import store from '../store'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: ()=>import('../views/HomeView.vue'),
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/Login.vue'),
    },
  ],
})

router.beforeEach((to, from, next) => {
  console.log(to.name)
  console.log(from.name)
  const isLogin = store.getters.getIsLogin
  // 检查目标路由是否需要登录
  if (to.path === '/login' && isLogin) {
    next('/'); // 已登录用户访问登录页时重定向到首页
  } else if (!isLogin && to.path !== '/login') {
    next('/login'); // 未登录用户访问非登录页时重定向到登录页
  } else {
    next(); // 允许通过
  }
})





export default router
